#!/usr/bin/env python2.6
# Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

import optparse
import os
import subprocess
import sys

ROOT=os.path.abspath(
  os.path.join(os.path.dirname(sys.argv[0]), '../../../'))
def rootPath(*args):
  return os.path.join(ROOT, *args)

HERE = rootPath('samples/belay/buzzer')
def herePath(*args):
  return os.path.join(HERE, *args)

sys.path.append(rootPath('tools'))
import utils

def GetOutputPath(mode):
  return rootPath(
    'compiler',
    utils.GetBuildRoot(utils.GuessOS(), mode, 'dartc'))

def BuildFling(mode):
  # Build dartc
  if subprocess.call([
      '../tools/build.py',
      '--mode=%s' % mode],
      cwd = rootPath('compiler')) != 0:
    return False
  if subprocess.call([
    rootPath('third_party/apache_ant/v1_7_1/bin/ant'),
      '-f', rootPath('client/fling/build.xml'),
      '-Dbuild.dir=%s' % GetOutputPath(mode),
      'build']) != 0:
    return False
  return True

def RunFling(mode):
  subprocess.call(
    [os.path.join(GetOutputPath(mode), 'fling/fling/fling'), 'BuzzerServer.dart'],
    cwd = herePath())

if __name__ == '__main__':
  parser = optparse.OptionParser()
  parser.add_option('--no-build',
    dest = 'build',
    action = 'store_false',
    default = True,
    help = 'Skip reubilding of fling')
  parser.add_option('--mode',
    dest = 'mode',
    default = "release",
    help = 'Mode to use when building dependencies (release or debug)')
  options, args = parser.parse_args()
  if not options.build or BuildFling(options.mode):
    RunFling(options.mode)
